package com.edushare.common.dao;

import java.util.HashMap;
import java.util.List;

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.query.SelectQuery;

import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.Departments;
import com.edushare.common.vo.GenericAudience;
import com.edushare.common.vo.Groups;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.Users;

public class GenericAudiencesDAO extends CayenneBasedDAO {
	public GenericAudiencesDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}

	@SuppressWarnings("unchecked")
	public List<GenericAudience> getAudiences(int sourceId, int sourceType) {
		Expression exp = Expression
				.fromString("sourceId = $sourceId and sourceType = $sourceType");
		HashMap<String, Integer> params = new HashMap<String, Integer>();
		params.put("sourceId", sourceId);
		params.put("sourceType", sourceType);
		SelectQuery query = new SelectQuery(GenericAudience.class, exp
				.expWithParameters(params));
		List lst = getDataContext().performQuery(query);
		return (List<GenericAudience>) lst;
	}

	public GenericAudience createGroupAudience(Groups group, int subset,
			int sourceId, int sourceType, Users creator, int inviteType) {
		return createAudience(GenericAudience.AUDIENCE_GROUP, group
				.getGroupId(), subset, sourceId, sourceType, creator,
				inviteType);
	}

	public GenericAudience createDeptAudience(Departments dept, int subset,
			int sourceId, int sourceType, Users creator, int inviteType) {
		return createAudience(GenericAudience.AUDIENCE_DEPT, dept
				.getDepartmentId(), subset, sourceId, sourceType, creator,
				inviteType);
	}

	public GenericAudience createCourseAudience(CourseInstances course,
			int subset, int sourceId, int sourceType, Users creator,
			int inviteType) {
		return createAudience(GenericAudience.AUDIENCE_COURSE, course
				.getCourseInstanceId(), subset, sourceId, sourceType, creator,
				inviteType);
	}

	public GenericAudience createUnivAudience(Universities univ, int subset,
			int sourceId, int sourceType, Users creator, int inviteType) {
		return createAudience(GenericAudience.AUDIENCE_UNIV, univ
				.getUniversityId(), subset, sourceId, sourceType, creator,
				inviteType);
	}

	public GenericAudience createAudience(int entityType, int entityId,
			int subset, int sourceId, int sourceType, Users creator,
			int inviteType) {
		GenericAudience ga = new GenericAudience();
		ga.setAudienceId(entityId);
		ga.setAudienceType(entityType);
		ga.setAudienceInviteType(inviteType);
		ga.setAudienceSubset(subset);

		ga.setSourceId(sourceId);
		ga.setSourceType(sourceType);
		ga.setCreator(creator);

		getDataContext().registerNewObject(ga);
		getDataContext().commitChanges();
		return ga;
	}
}
